<template>
  <q-page class="q-pa-md">
    <div class="row items-center">
      <div class="q-pb-md text-h5">
        {{ pageTitle }}
        <span class="text-subtitle1">{{$t('列表')}}</span>
      </div>
      <q-space></q-space>
      <search-bar-toggle-btn v-model="searchBarVisibility"></search-bar-toggle-btn>
    </div>
    <div v-show="searchBarVisibility" class="q-pa-sm shadow-2 q-mb-md items-center">
      <div class="row q-col-gutter-sm q-mb-sm">
        <div class="col-xs-12 col-sm-6 col-md-5 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">{{$t('客商ID')}}</div>
          <div class="col-8">
            <q-input v-model="fpsReq.mfId" :hide-bottom-space="true" :readonly="listDataLoadingState"
              clearable dense :maxlength="30" outlined square stack-label @focus="ui.select"
              @keyup.enter="loadListData(2)" />
          </div>
        </div>
        <div class="col-xs-12 col-sm-6 col-md-5 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">{{$t('关键字')}}</div>
          <div class="col-8">
            <q-input v-model="fpsReq.mfName" :hide-bottom-space="true" :readonly="listDataLoadingState"
              clearable dense :maxlength="30" outlined square stack-label @focus="ui.select"
              @keyup.enter="loadListData(2)" />
          </div>
        </div>
        <div>
          <q-btn :disable="listDataLoadingState" color="primary" icon="search" :label="$t('查询')" @click="loadListData(2)" no-caps />
        </div>
        <div>
          <filter-options-cfg v-model:option-list="fpsInfo.filtersInfo"
            @update-filter-options-for-save="fpsAssist.saveFilterOptions">
          </filter-options-cfg>
        </div>
      </div>
      <div class="row q-col-gutter-sm">
        <div v-if="$d.actualFieldShown.isCustomer && fpsInfo.filtersInfo?.isCustomer?.show"
          class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isCustomer" :disable="listDataLoadingState" :false-value="null" dense
            :label="$t('客户')" no-caps @update:model-value="loadListData(2)" />
        </div>
        <div v-if="$d.actualFieldShown.isVendor && fpsInfo.filtersInfo?.isVendor?.show"
          class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isVendor" :disable="listDataLoadingState" :false-value="null" dense
            :label="$t('供应商')" no-caps @update:model-value="loadListData(2)" />
        </div>
        <div v-if="$d.actualFieldShown.isPayer && fpsInfo.filtersInfo?.isPayer?.show"
          class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isPayer" :disable="listDataLoadingState" :false-value="null" dense
            :label="$t('结算方')" no-caps @update:model-value="loadListData(2)" />
        </div>
        <div v-if="$d.actualFieldShown.isStorer && fpsInfo.filtersInfo?.isStorer?.show"
          class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isStorer" :disable="listDataLoadingState" :false-value="null" dense
            :label="$t('货主')" no-caps @update:model-value="loadListData(2)" />
        </div>
        <div v-if="$d.actualFieldShown.isForwarder && fpsInfo.filtersInfo?.isForwarder?.show"
          class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isForwarder" :disable="listDataLoadingState" :false-value="null" dense
            :label="$t('货代')" no-caps @update:model-value="loadListData(2)" />
        </div>
        <div v-if="$d.actualFieldShown.isCustomsBroker && fpsInfo.filtersInfo?.isCustomsBroker?.show"
          class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isCustomsBroker" :disable="listDataLoadingState" :false-value="null" dense
            :label="$t('报关行')" no-caps @update:model-value="loadListData(2)" />
        </div>
        <div v-if="$d.actualFieldShown.isCarrier && fpsInfo.filtersInfo?.isCarrier?.show"
          class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isCarrier" :disable="listDataLoadingState" :false-value="null" dense
            :label="$t('运输行')" no-caps @update:model-value="loadListData(2)" />
        </div>
        <div v-if="$d.actualFieldShown.isConsignee && fpsInfo.filtersInfo?.isConsignee?.show"
          class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isConsignee" :disable="listDataLoadingState" :false-value="null" dense
            :label="$t('收货人')" no-caps @update:model-value="loadListData(2)" />
        </div>
        <div v-if="$d.actualFieldShown.isEndUser && fpsInfo.filtersInfo?.isEndUser?.show"
          class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isEndUser" :disable="listDataLoadingState" :false-value="null" dense
            :label="$t('终端用户')" no-caps @update:model-value="loadListData(2)" />
        </div>
        <div v-if="$d.actualFieldShown.isDecClient && fpsInfo.filtersInfo?.isDecClient?.show"
          class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isDecClient" :disable="listDataLoadingState" :false-value="null" dense
            :label="$t('报关行委托方')" no-caps @update:model-value="loadListData(2)" />
        </div>
        <div v-if="$d.actualFieldShown.isTradeProxy && fpsInfo.filtersInfo?.isTradeProxy?.show"
          class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isTradeProxy" :disable="listDataLoadingState" :false-value="null" dense
            :label="$t('商贸代理')" no-caps @update:model-value="loadListData(2)" />
        </div>
        <div v-if="fpsInfo.filtersInfo?.isEnabled?.show" class="col-xs-12 col-sm-6 col-md-3 col-lg-2">
          <q-toggle v-model="fpsReq.isEnabled" :disable="listDataLoadingState" dense :label="$t('有效')" no-caps
            toggle-indeterminate @update:model-value="loadListData(2)" />
        </div>
      </div>
    </div>

    <div class="shadow-2">
      <q-table v-model:pagination="fpsInfo.paginationInfo" :columns="fpsInfo.columnsInfo" :hide-pagination="true"
        :loading="listDataLoadingState" :rows="$d.tableData"
        :visible-columns="fpsInfo.visibleColumns" binary-state-sort
        class="generic-sticky-header-table"
        color="primary" dense flat row-key="mfId" separator="cell" @request="fpsAssist.onDataTableRequest"
        @row-dblclick="(evt, row) => {fpsNav.gotoDetail(row.mfId)}">
        <template v-slot:top="props">
          <div class="row q-gutter-sm">
            <q-btn v-if="fx.hasModifyRight('Comm.Mf.Edit')" color="primary" icon="add" :label="$t('新建')" no-caps
              @click="fx.router.push({ name: '/comm/basic/mf/create' })" />
            <q-btn v-if="fx.hasModifyRight('Comm.Mf.Edit')" color="primary" icon="fas fa-file-import" :label="$t('客商批量导入')" no-caps
              @click="onImportMfsByExcel" />
          </div>
          <q-space />
          <q-btn dense flat icon="save_alt" :title="$t('导出Excel')" @click="downloadExcel" />
          <table-col-options-cfg v-model:visible-columns="fpsInfo.visibleColumns"
            v-model:table-columns="fpsInfo.columnsInfo" class="q-mx-sm"
            @update-col-options-for-save="fpsAssist.saveColOptions"></table-col-options-cfg>
          <q-btn :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'" :ripple="false"
             :title="props.inFullscreen ? $t('退出全屏') : $t('全屏显示')" dense flat @click="props.toggleFullscreen" />
        </template>
        <template v-slot:no-data>
          <div class="full-width items-center justify-center row">
            <q-icon name="error_outline" />
            {{$t('无数据')}}
            <q-btn :disable="listDataLoadingState" :loading="listDataLoadingState" class="q-ml-sm" dense
              flat icon="refresh" size="sm" :title="$t('刷新')" no-caps @click="loadListData"></q-btn>
          </div>
        </template>
        <!--类型列-->
        <template v-slot:body-cell-type="props">
          <q-td :props="props">
            <q-badge v-if="props.row.isCustomer" class="q-mr-xs" color="primary" :label="$t('客户')" no-caps />
            <q-badge v-if="props.row.isVendor" class="q-mr-xs" color="primary" :label="$t('供应商')" no-caps  />
            <q-badge v-if="props.row.isPayer" class="q-mr-xs" color="primary" :label="$t('结算方')" no-caps />
            <q-badge v-if="props.row.isStorer" class="q-mr-xs" color="primary" :label="$t('货主')" no-caps />
            <q-badge v-if="props.row.isForwarder" class="q-mr-xs" color="primary"  :label="$t('货代')" no-caps />
            <q-badge v-if="props.row.isCustomsBroker" class="q-mr-xs" color="primary" :label="$t('报关行')" no-caps />
            <q-badge v-if="props.row.isCarrier" class="q-mr-xs" color="primary" :label="$t('运输行')" no-caps />
            <q-badge v-if="props.row.isConsignee" class="q-mr-xs" color="primary" :label="$t('收货人')" no-caps />
            <q-badge v-if="props.row.isEndUser" class="q-mr-xs" color="primary" :label="$t('终端用户')" no-caps />
            <q-badge v-if="props.row.isDecClient" class="q-mr-xs" color="primary" :label="$t('报关行委托方')" no-caps />
            <q-badge v-if="props.row.isTradeProxy" class="q-mr-xs" color="primary" :label="$t('商贸代理')" no-caps />
          </q-td>
        </template>
        <!--状态列-->
        <template v-slot:body-cell-state="props">
          <q-td :props="props" auto-width>
            <q-badge :color="props.row.isEnabled ? 'positive' : 'grey-6'"
              :label="props.row.isEnabled ? $t('有效') : $t('无效')" />
          </q-td>
        </template>
        <!--操作列-->
        <template v-slot:body-cell-operation="props">
          <q-td :props="props" auto-width>
            <q-btn class="q-mr-xs btn-in-row" color="primary" dense :label="$t('查看')" no-caps
              @click="evt=> fpsNav.gotoDetail(props.row.mfId, evt)" />
            <q-btn v-if="fx.hasModifyRight('Comm.Mf.Edit')" class="btn-in-row" color="primary" dense :label="$t('编辑')" no-caps
              @click="evt=> fpsNav.gotoEdit(props.row.mfId, evt)" />
          </q-td>
        </template>
        <!-- 底部分页条 -->
        <template v-slot:bottom>
          <paging-bar :loading-state="listDataLoadingState" :pageNo="fpsReq.pageNo" :pageSize="fpsReq.pageSize"
            :totalAmount="fpsInfo.totalAmount" @pagesize-changed="fpsAssist.onPageSizeChanged"
            @go-to-page="fpsNav.gotoPage" />
        </template>
      </q-table>
    </div>

    <!--批量导入-->
    <q-dialog v-model="showingMfImportDlg" transition-hide="none" transition-show="none">
      <q-card class="card">
        <q-card-section class="q-pa-sm">
          <div class="text-h6">
            {{$t('批量导入')}}
            <a class="text-body2" href="javascript:void(0)"
              @click="nw.downloadFile('/comm/res/download/mf-import-template.xlsx')">导入模板下载</a>
          </div>
        </q-card-section>
        <q-separator />
        <q-banner v-if="errorMessageForMfImport" class="text-white bg-red q-mt-sm q-mx-sm" dense inline-actions>
          {{ errorMessageForMfImport }}
        </q-banner>
        <div class="q-pa-sm">
          <div class="row justify-between">
            <input ref="mfListExcelFileInput" type="file" />
            <q-checkbox v-if="props.enableTruncateImport" v-model="truncateFirstForMfImport" color="primary q-pa-xs"
              dense>
              {{$t('清空导入')}}
              <q-icon class="q-mb-xs" color="warning" name="fas fa-exclamation">
                <q-tooltip anchor="center right" self="center left" transition-hide="none" transition-show="none">
                  {{$t('勾选此项系统会尝试清空掉全部现有数据，慎用')}}
                </q-tooltip>
              </q-icon>
            </q-checkbox>
          </div>
        </div>
        <q-separator class="separator" />
        <q-card-actions align="right">
          <q-btn color="primary" :label="$t('确定')" no-caps @click="importMfListExcel"  />
          <q-btn v-close-popup color="primary" :label="$t('取消')" no-caps outline unelevated  />
        </q-card-actions>
        <q-inner-loading :showing="importMfExcelState">
          <q-spinner color="primary" size="50px" />
        </q-inner-loading>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'mfListStd'
}
</script>
<script lang="ts" setup>
import {useFpsHelper} from '../../hooks/fpsHelper'
import {useTitleHelper} from '../../hooks/titleHelper'
import {reactive, ref} from 'vue'
import {GetMfListReq, GetMfListResp, MfFullForImport} from '../../defs/mf'
import {ColumnInfo, FilterInfo, MfFieldOptionsDef} from '../../defs/comm'
import dayjs from 'dayjs'
import _ from 'lodash'
import { useI18n } from 'vue-i18n'
const {t} = useI18n()

const pageTitle = t('客商管理')
useTitleHelper(pageTitle)

interface PropsDef {
  // 页面选项，字段选项
  fieldOptions?: MfFieldOptionsDef
  // 清空导入
  enableTruncateImport?: boolean
}

let props = withDefaults(defineProps<PropsDef>(), {
  fieldOptions: () => {
    return {}
  },
  enableTruncateImport: false
})


// 是否处于数据列表加载的状态
const listDataLoadingState = ref(false)

// 查询参数
const fpsReq: GetMfListReq = reactive({
  mfId: null,
  mfName: null,
  isPayer: null,
  isStorer: null,
  isVendor: null,
  isForwarder: null,
  isCustomsBroker: null,
  isCarrier: null,
  isConsignee: null,
  isCustomer: null,
  isEndUser: null,
  isDecClient: null,
  isTradeProxy: null,
  isEnabled: null,
  pageNo: 1,
  pageSize: 40,
  isDescending: false,
  orderBy: null
})
const columnsDefine: ColumnInfo[] = [
  {
    name: 'operation',
    label: t('操作'),
    field: 'operation',
    align: 'left',
    defOrder: 1,
    defVisible: true
  },
  {
    label: t('客商ID'),
    name: 'mfId',
    field: 'mfId',
    sortable: true,
    align: 'left',
    defOrder: 2,
    defVisible: true
  },
  {
    label: t('简称'),
    name: 'abbrName',
    field: 'abbrName',
    sortable: true,
    align: 'left',
    defOrder: 3,
    defVisible: true
  },
  {
    label: t('中文全称'),
    name: 'fullNameC',
    field: 'fullNameC',
    sortable: true,
    align: 'left',
    defOrder: 4,
    defVisible: true
  },
  {
    label: t('英文全称'),
    name: 'fullNameE',
    field: 'fullNameE',
    sortable: true,
    align: 'left',
    defOrder: 5,
    defVisible: true
  },
  {
    label: t('类型'),
    name: 'type',
    field: 'type',
    sortable: false,
    align: 'left',
    defOrder: 6,
    defVisible: true
  },
  {
    label: t('状态'),
    name: 'state',
    field: 'state',
    sortable: false,
    align: 'left',
    defOrder: 7,
    defVisible: true
  },
  {
    label: t('自定义1'),
    name: 'userDef1',
    field: 'userDef1',
    align: 'left',
    defOrder: 8,
    defVisible: false
  },
  {
    label: t('自定义2'),
    name: 'userDef2',
    field: 'userDef2',
    align: 'left',
    defOrder: 9,
    defVisible: false
  },
  {
    label: t('自定义3'),
    name: 'userDef3',
    field: 'userDef3',
    align: 'left',
    defOrder: 10,
    defVisible: false
  },
  {
    label: t('自定义4'),
    name: 'userDef4',
    field: 'userDef4',
    align: 'left',
    defOrder: 11,
    defVisible: false
  },
  {
    label: t('自定义5'),
    name: 'userDef5',
    field: 'userDef5',
    align: 'left',
    defOrder: 12,
    defVisible: false
  },
  {
    label: t('自定义6'),
    name: 'userDef6',
    field: 'userDef6',
    align: 'left',
    defOrder: 13,
    defVisible: false
  },
  {
    label: t('自定义7'),
    name: 'userDef7',
    field: 'userDef7',
    align: 'left',
    defOrder: 14,
    defVisible: false
  },
  {
    label: t('自定义8'),
    name: 'userDef8',
    field: 'userDef8',
    align: 'left',
    defOrder: 15,
    defVisible: false
  },
  {
    label: t('自定义9'),
    name: 'userDef9',
    field: 'userDef9',
    align: 'left',
    defOrder: 16,
    defVisible: false
  },
  {
    label: t('自定义10'),
    name: 'userDef10',
    field: 'userDef10',
    align: 'left',
    defOrder: 17,
    defVisible: false
  }
]

// 导入相关
// 是否处于Excel上传中的状态
let importMfExcelState = ref(false)
// 清空上传
let truncateFirstForMfImport = ref(false)
// 错误提示内容
let errorMessageForMfImport = ref('')
// 批量导入对话框 显示/隐藏
let showingMfImportDlg = ref(false)

let $d = reactive({
  tableData: [] as MfFullForImport[],
  // 实际字段开关状态(与props混合后的结果)
  actualFieldShown: {
    isCustomer: {
      isShown: true
    },
    isVendor: {
      isShown: true
    },
    isPayer: {
      isShown: true
    },
    isStorer: {
      isShown: true
    },
    isForwarder: {
      isShown: true
    },
    isCustomsBroker: {
      isShown: true
    },
    isCarrier: {
      isShown: true
    },
    isConsignee: {
      isShown: true
    },
    isEndUser: {
      isShown: true
    },
    isDecClient: {
      isShown: true
    },
    isTradeProxy: {
      isShown: true
    },
    userDef1: {
      isShown: false
    },
    userDef2: {
      isShown: false
    },
    userDef3: {
      isShown: false
    },
    userDef4: {
      isShown: false
    },
    userDef5: {
      isShown: false
    },
    userDef6: {
      isShown: false
    },
    userDef7: {
      isShown: false
    },
    userDef8: {
      isShown: false
    },
    userDef9: {
      isShown: false
    },
    userDef10: {
      isShown: false
    }
  } as MfFieldOptionsDef,
  // 查询条件显示/隐藏配置
  filterOptionList: {
    isCustomer: {
      label: t('客户'),
      show: true,
      order: 1
    },
    isVendor: {
      label: t('供应商'),
      show: true,
      order: 2
    },
    isPayer: {
      label: t('结算方'),
      show: true,
      order: 3
    },
    isStorer: {
      label: t('货主'),
      show: true,
      order: 4
    },
    isForwarder: {
      label: t('货代'),
      show: true,
      order: 5
    },
    isCustomsBroker: {
      label: t('报关行'),
      show: true,
      order: 6
    },
    isCarrier: {
      label: t('运输行'),
      show: true,
      order: 7
    },
    isConsignee: {
      label: t('收货人'),
      show: true,
      order: 8
    },
    isEndUser: {
      label: t('终端用户'),
      show: true,
      order: 9
    },
    isDecClient: {
      label: t('报关行委托方'),
      show: true,
      order: 10
    },
    isTradeProxy: {
      label: t('商贸代理'),
      show: true,
      order: 11
    },
    isEnabled: {
      label: t('有效'),
      show: true,
      order: 12
    }
  } as Record<string, FilterInfo>
})

const loadListData = function (resetFpsReq?: number) {
  if (resetFpsReq) {
    if (resetFpsReq >= 1) {
      fpsReq.pageNo = 1
    }
    if (resetFpsReq >= 2) {
      fpsReq.orderBy = ''
      fpsReq.isDescending = false
    }
  }
  listDataLoadingState.value = true
  $f.axios.get<GetMfListResp>('/comm/mf/get-mf-list', {params: fpsReq})
    .then(result => {
      fpsAssist.handleGenericFpsResp(result.data)
      $d.tableData = result.data.mfs
      fpsAssist.saveFpsReq(fpsReq)
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      listDataLoadingState.value = false
    })
}

let mfListExcelFileInput = ref()
// 批量导入
const importMfListExcel = function () {
  importMfExcelState.value = true
  let formData = new window.FormData()
  formData.append('dataFile', mfListExcelFileInput.value.files[0])
  formData.append('truncateFirst', String(truncateFirstForMfImport.value))
  $f.axios
    .post('/comm/mf/import-mfs', formData)
    .then(() => {
      showingMfImportDlg.value = false
      loadListData(2)
    })
    .catch((err) => {
      if (err.response?.data?.errorList?.length) {
        showingMfImportDlg.value = false
        $f.ui.showErrorListDlg(err?.response?.data)
      } else {
        errorMessageForMfImport.value = $f.getAxiosErrMsg(err)
      }
    })
    .finally(() => {
      importMfExcelState.value = false
    })
}

// 客商批量导入
const onImportMfsByExcel = function () {
  showingMfImportDlg.value = true
  errorMessageForMfImport.value = ''
  truncateFirstForMfImport.value = false
}
// 导出EXCEL
const downloadExcel = function () {
  let timeStamp = Date.now()
  let formattedString = dayjs(timeStamp).format('YYYYMMDDHHmmss')
  let fileName = 'Mf_' + formattedString + '.xlsx'
  let params = $f.misc.makeSimpleQueryObj(fpsReq, [], {pageNo: 1, pageSize: 0x7fffffff})
  let url = $f.misc.makeUrlWithQueryParam('/comm/mf/get-mf-list-excel', params)
  $f.nw.downloadFileWithAuth(url, fileName, false)
}

// FPS配置
const {
  fpsInfo,
  fpsAssist,
  fpsNav,
  searchBarVisibility
} = useFpsHelper('/comm/basic/mf',
  '/comm/basic/mf/detail',
  '/comm/basic/mf/create',
  '/comm/basic/mf/edit',
  fpsReq, columnsDefine,
  $d.filterOptionList,
  loadListData)

// ************  处理field-options相关内容 ************
// 字段的显示/隐藏
$f.misc.simpleAssign($d.actualFieldShown, props.fieldOptions)

// 处理自定义label
_.forEach(props.fieldOptions, (opt, field) => {
  if (opt?.label) {
    let theCol = _.find(fpsInfo.columnsInfo, {field: field})
    if (theCol) {
      theCol.label = opt.label
    }
  }
})
// 移除表格中不显示的列
fpsInfo.columnsInfo = _.reject(fpsInfo.columnsInfo, (v) => {
  return $d.actualFieldShown[v.field]?.isShown == false
})

// 查询条件处理
fpsInfo.filtersInfo = _.omitBy(fpsInfo.filtersInfo, (value, key) => {
  return $d.actualFieldShown[key]?.isShown == false
})

const fx = $f
const ui = fx.ui
const nw = fx.nw

</script>
